import React from 'react';
import { Row, Col, Form, InputNumber, Input, Button, Table, Select, Modal, Popconfirm, message } from 'antd';
const R = require('ramda');
import BizParams from '../../../components/commons/BizParams'
import BuyerAccountDetail from '../../../components/customer/components/buyerAccountDetail';

const FormItem = Form.Item;
const view = "view"

export default Form.create({ wrappedComponentRef: true })(class EditBuyer extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            open: false,
            disabled: true,
            type: "",
        }
    }

    handleCancel = () => {
        this.props.form.resetFields()
        this.setState({ open: false })
        this.props.dispatch({
            type: 'customerManage/setBuyer',
            payload: {
                recAcc: "",
            }
        });
    }

    handleOpen = (type) => {
        this.state.type = type;
        this.setState({ open: true })
    }

    handleOpenAccount = (dataSource) => {
        this.buyerAccountDetail.handleOpen(dataSource);
    }

    handleAddOrUpdateAccount = values => {
        let dataSource = this.props.dataSource ? this.props.dataSource : {};
        dataSource.accounts = (dataSource.accounts ? dataSource.accounts : []).concat(values);
        this.props.dispatch({ type: 'customerManage/refreshState', payload: { buyer: dataSource } });
    }

    handleDeleteAccount = (target) => {
        let dataSource = this.props.dataSource ? this.props.dataSource : {};
        let accounts = dataSource.accounts ? dataSource.accounts : [];
        dataSource.accounts.splice(accounts.findIndex(item => item.id === target.id), 1);
        this.props.dispatch({ type: 'customerManage/refreshState', payload: { dataSource } });
    }

    handleConfirm = () => {
        this.props.form.validateFields((errors, values) => {
            let dataSource = R.isNil(this.props.dataSource) ? {} : this.props.dataSource
            if (errors) return;

            if(!dataSource.accounts || dataSource.accounts.length == 0){
                message.error("请至少输入一个付款账号信息");
                return;
            }

            if (this.state.type == view) {
                return;
            }

            let linkman = values;
            let type = "";
            if (this.state.type == "add") {
                type = "customerManage/addBuyer";

            } else if (this.state.type == "edit") {
                type = "customerManage/updateBuyer";

            }

            this.props.dispatch({
                type: type,
                payload: {
                    cstid: this.props.cstId,
                    id: dataSource.id,
                    name: values.name,
                    country: values.country,
                    address: values.address,
                    linkman: values.linkman,
                    telephone: values.telephone,
                    accounts: dataSource.accounts ? dataSource.accounts : [],
                    onSuccess: () => {
                        this.handleCancel();
                    }

                }
            })


        })
    }

    columns = [
        { title: '收汇银行', dataIndex: 'bankName', key: 'bankName' },
        { title: '收汇账号', dataIndex: 'account', key: 'account' },
        { title: '账号名称', dataIndex: 'accountName', key: 'accountName' },
        { title: '创建人', dataIndex: 'creatorName', key: 'creatorName' },
        { title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
        {
            title: '操作', key: 'key_oprator',
            render: (text, record, index) => {
                return (
                    <span style={{display: this.props.disabled || this.state.type == view ? 'none' : 'block'}}>
                        <a href="#" onClick={this.handleDeleteAccount.bind(this, record)}>删除</a>
                    </span>
                );
            }
        }
    ];

    render() {
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = { labelCol: { xs: { span: 8 }, sm: { span: 8 } }, wrapperCol: { xs: { span: 15 }, sm: { span: 14 } } };
        let dataSource = R.isNil(this.props.dataSource) ? {} : this.props.dataSource;
        let footer = [
            <Popconfirm onConfirm={this.handleConfirm.bind(this, true)} cancelText="否" okText="是"
                placement="leftTop" title={'为了保持存量数据的一致性，境外买家新增之后不能修改只能删除，请确认！'}>
                <Button key="ok" size="large" style={{display: this.props.disabled || this.state.type == view ? 'none' : 'inline-block'}}>确定</Button>
            </Popconfirm>,
            <Button key="cancel" size="large" onClick={this.handleCancel.bind(this, true)}>取消</Button>
        ];
        return (
            <div>
                <Modal visible={this.state.open} title={"添加境外供应商"} width={700} wrapClassName="vertical-center-modal"
                    footer={footer} onOk={this.handleConfirm} onCancel={this.handleCancel}>
                    <Form>
                        <Row>
                            <Col span={30}>
                                <FormItem {...{ labelCol: { sm: { span: 4 } }, wrapperCol: { sm: { span: 18 } } }} label="名称" hasFeedback>
                                    {getFieldDecorator('name', {
                                        rules: [{
                                            required: true, message: '请输入名称'
                                        }],
                                        initialValue: dataSource.name
                                    })(
                                        <Input maxLength="100" disabled={this.props.disabled || this.state.type == view} />
                                        )}
                                </FormItem></Col>

                        </Row>
                        <Row>
                            <Col span={30}>
                                <FormItem {...{ labelCol: { sm: { span: 4 } }, wrapperCol: { sm: { span: 18 } } }} label="地址" hasFeedback>
                                    {getFieldDecorator('address', {
                                        rules: [{
                                            required: true, message: '请输入地址'
                                        }],
                                        initialValue: dataSource.address
                                    })(
                                        <Input maxLength="200" disabled={this.props.disabled || this.state.type == view} />
                                        )}
                                </FormItem></Col>
                        </Row>
                        <Row>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="国家" hasFeedback>
                                    {getFieldDecorator('country', {
                                        rules: [{
                                            required: true, message: '请输入国家'
                                        }],
                                        initialValue: R.isNil(dataSource.country) ? '' : dataSource.country + ''
                                    })(
                                        <BizParams sprCode={"country"} style={{ width: '100%' }} blank={true} disabled={this.props.disabled || this.state.type == view}/>
                                        )}
                                </FormItem></Col>
                            <Col span={10} style={{ width: 250 }}>
                                <FormItem {...formItemLayout} label="联系人" hasFeedback>
                                    {getFieldDecorator('linkman', {
                                        rules: [{
                                            required: true, message: '请输入联系人'
                                        }],
                                        initialValue: dataSource.linkman
                                    })(
                                        <Input maxLength="30" disabled={this.props.disabled || this.state.type == view} />
                                        )}
                                </FormItem></Col>
                        </Row>
                        <Row>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="电话" hasFeedback>
                                    {getFieldDecorator('telephone', {
                                        rules: [{
                                            required: false, message: '请输入电话'
                                        }],
                                        initialValue: R.isNil(dataSource.telephone) ? '' : dataSource.telephone
                                    })(
                                        <Input maxLength="30" disabled={this.props.disabled || this.state.type == view} />
                                        )}
                                </FormItem></Col>
                        </Row>
                    </Form>
                    <Row>
                        <Col span={3} style={{ float: 'right', marginRight: 15, marginBottom: 15, display: this.props.disabled || this.state.type == view ? 'none' : 'block' }}>
                            <Button type="primary" icon="plus" size={'default'}
                                onClick={this.handleOpenAccount.bind(this, { buyerId: dataSource.id })}
                            >新增账号</Button>
                        </Col>
                    </Row>
                    <Table rowKey={record => record.id} columns={this.columns} dataSource={dataSource.accounts} bordered={true} size={'small'} pagination={false} />
                </Modal>
                <BuyerAccountDetail wrappedComponentRef={(inst) => this.buyerAccountDetail = inst} handleAddOrUpdateAccount={this.handleAddOrUpdateAccount} />
            </div>
        );
    }
})